package com.fishingwithme.android.ui.screens.my.settings

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Person
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Snackbar
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import coil.compose.rememberAsyncImagePainter
import com.fishingwithme.android.R
import com.fishingwithme.android.data.local.PreferencesManager
import com.fishingwithme.android.data.model.User
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.ui.viewmodels.UserEditViewModel
import com.fishingwithme.android.utils.ImageUtils
import com.google.gson.Gson
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import java.io.File

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UserEditScreen(navController: NavController) {
    val viewModel = hiltViewModel<UserEditViewModel>()
    val uiState by viewModel.uiState.collectAsState()
    val scrollState = rememberScrollState()

    // 获取PreferencesManager实例
    val context = LocalContext.current
    val preferencesManager = EntryPointAccessors.fromApplication(
        context.applicationContext,
        UserEditScreenHiltEntryPoint::class.java
    ).preferencesManager()

    // Get user data
    val user by preferencesManager.getLoginUserObj().collectAsState(initial = null)

    // 初始化表单数据
    LaunchedEffect(user) {
        user?.let {
            viewModel.setInitialData(it)
        }
    }

    // 处理保存成功
    LaunchedEffect(uiState.isSaveSuccessful) {
        if (uiState.isSaveSuccessful) {
            // 显示成功提示
            // 更新本地缓存的用户数据
            user?.let { it ->
                val updatedUser = it.copy(
                    nickname = uiState.nickname!!,
                    avatarUrl = uiState.avatarUrl
                )
                // 使用PreferencesManager提供的方法保存用户数据
                preferencesManager.saveLoginUser(updatedUser)
            }

            // 导航回上一页
            navController.navigateUp()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("") },
                navigationIcon = {
                    IconButton(onClick = { navController.navigateUp() }) {
                        Icon(Icons.Default.ArrowBack, contentDescription = "Back")
                    }
                }
            )
        }
    ) { paddingValues ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(scrollState)
                    .padding(horizontal = AppDimensions.SPACING_16)
            ) {
                // 头像上传区域
                AvatarUploadSection(
                    avatarUrl = uiState.avatarUrl,
                    onSaveAvatar = viewModel::uploadAndSaveAvatar
                )

                Spacer(modifier = Modifier.height(AppDimensions.SPACING_24))

                // 表单区域
                FormSection(
                    uiState = uiState,
                    viewModel = viewModel,
                    user = user
                )

                Spacer(modifier = Modifier.height(AppDimensions.SPACING_32))
            }

            // 加载状态
            if (uiState.isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background.copy(alpha = 0.7f)),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }

            // 错误提示
            uiState.error?.let {
                Snackbar(
                    modifier = Modifier
                        .align(Alignment.BottomCenter)
                        .padding(AppDimensions.SPACING_16),
                    action = { TextButton(onClick = viewModel::clearError) { Text("关闭") } }
                ) {
                    Text(text = it)
                }
            }
        }
    }
}

@Composable
private fun AvatarUploadSection(
    avatarUrl: String?,
    onSaveAvatar: (File) -> Unit
) {
    val context = LocalContext.current
    val isUploading = remember { mutableStateOf(false) }

    // Image picker launcher
    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            isUploading.value = true
            // Use ImageUtils to process the selected image
            val compressedFile = ImageUtils.compressImage(context, uri)
            compressedFile?.let { file ->
                // Upload the file
                onSaveAvatar(file)
            } ?: run {
                //TODO: 需要处理图片压缩问题.
            }
            isUploading.value = false
        }
    }

    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            modifier = Modifier
                .size(AppDimensions.ICON_SIZE_120)
                .clip(CircleShape)
                .clickable(onClick = { imagePickerLauncher.launch("image/*") })
                .background(MaterialTheme.colorScheme.primaryContainer),
            contentAlignment = Alignment.Center
        ) {
            if (avatarUrl != null) {
                // Check if avatarUrl is a file path or URL
                val imageUri = avatarUrl.toUri()
                Image(
                    painter = rememberAsyncImagePainter(imageUri),
                    contentDescription = "User Avatar",
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            } else {
                Icon(
                    imageVector = Icons.Default.Person,
                    contentDescription = "Upload Avatar",
                    tint = MaterialTheme.colorScheme.onPrimaryContainer,
                    modifier = Modifier.size(AppDimensions.ICON_SIZE_64)
                )
            }
        }

        Text(
            text = stringResource(R.string.change_avatar),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier
                .padding(top = AppDimensions.SPACING_8)
                .clickable { imagePickerLauncher.launch("image/*") }
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun FormSection(
    uiState: UserEditViewModel.UserEditUiState,
    viewModel: UserEditViewModel,
    user: User?
) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)
    ) {
        Column(modifier = Modifier.padding(AppDimensions.SPACING_16)) {
            // 昵称字段

            OutlinedTextField(
                value = uiState.nickname ?: "",
                onValueChange = viewModel::setNickname,
                label = { Text(stringResource(R.string.nickname)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16),
                singleLine = true,
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.AccountCircle,
                        contentDescription = null
                    )
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // 用户名（只读）
            OutlinedTextField(
                value = user?.username ?: "",
                onValueChange = {},
                label = { Text(stringResource(R.string.username)) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = AppDimensions.SPACING_16),
                singleLine = true,
                enabled = false,
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Default.Person,
                        contentDescription = null
                    )
                },
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )

            // 保存按钮
            Button(
                onClick = viewModel::saveAllChanges,
                enabled = uiState.nickname != null && uiState.nickname!!.isNotBlank() && !uiState.isLoading,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(AppDimensions.BUTTON_HEIGHT_48),
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            ) {
                Text(stringResource(R.string.save_changes))
            }
        }
    }
}


// Hilt入口点接口
@EntryPoint
@InstallIn(SingletonComponent::class)
interface UserEditScreenHiltEntryPoint {
    fun preferencesManager(): PreferencesManager
}